import { ios_check } from '@/api/distribution/index.js'

export function Init() {
  return new Promise((resolve, reject) => {
    //使用uni.getProvider来获取通道
    uni.getProvider({
      service: 'payment',
      success: (res) => {
        let iapChannel = res.providers.find((channel) => {
          return channel.id === 'appleiap'
        })
        //成功之后会返回通道
        resolve(iapChannel)
      },
      fail: (err) => {
        reject(err)
      },
    })
  })
}
export function finishTransaction(transaction, iapChannel) {
  console.log('关闭订单')
  return new Promise((resolve, reject) => {
    iapChannel.finishTransaction(
      transaction,
      (res) => {
        console.log('关闭订单成功', res)
        resolve(res)
      },
      (err) => {
        reject(err)
      },
    )
  })
}

export function restore(iapChannel, username) {
  console.log('获取苹果服务器已支付且未关闭的交易列表')
  return new Promise((resolve, reject) => {
    iapChannel?.restoreCompletedTransactions(
      {
        manualFinishTransaction: true,
        username,
      },
      (res) => {
        resolve(res)
      },
      (err) => {
        reject(err)
      },
    )
  })
}

export function getReview(iapChannel, info) {
  //请求是否有已完成未关闭的订单
  restore(iapChannel, info?.order_sn).then((res) => {
    //如果有并且状态为已支付则请求关闭并回调给后端
    console.log(res)
    if (res.length > 0) {
      //轮询关闭订单
      res.map((item) => {
        finishTransaction(item, iapChannel)
        //如果状态为已完成的状态
        if (item.transactionState == '1') {
          //后端逻辑，此处省略，通常是完成上报凭证的操作，来完成补单
          console.log(item, '未完成的单子')
          //请求后端接口上传支付凭证
          ios_check(info).then((res) => {
            console.log(res)
            uni.showToast({
              icon: 'none',
              title: '订单已支付成功，请稍后留意咪婴币',
            })
          })
        }
      })
    }
  })
}

/**
 * 调用ID为“appleiap”的PaymentChannel对象的requestOrder方法，像Appstore请求有效的商品详情。
 * 注意：IAP支付必须在调用payment.request方法之前，调用requestOrder方法，否则调用payment.request将会报错。
 */
export function requestOrder(iapChannel, productIds) {
  uni.showLoading({
    title: '支付中请稍等',
    mask: true,
  })
  return new Promise((resolve, reject) => {
    iapChannel.requestOrder(
      productIds,
      (orderList) => {
        //必须调用此方法才能进行 iap 支付
        console.log('requestOrder success: ' + JSON.stringify(orderList))
        resolve(orderList)
        uni.hideLoading()
      },
      (e) => {
        console.log('requestOrder failed: ' + JSON.stringify(e))
        uni.hideLoading()
        uni.showToast({
          icon: 'none',
          title: '当前环境不支持支付',
        })
        reject(e)
      },
    )
  })
}
